# Maintainer: Feng Shu <tumashu@163.com>

_realname=leveldb
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.23
pkgrel=2
pkgdesc="A fast and lightweight key/value database library (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://github.com/google/leveldb"
license=('BSD')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-benchmark"
             "${MINGW_PACKAGE_PREFIX}-gtest"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("${_realname}-${pkgver}.tar.gz::https://github.com/google/leveldb/archive/${pkgver}.tar.gz"
        001-snappy-optional.patch
        leveldb-unbundle-gtest-benchmark.patch)
sha256sums=('9a37f8a6174f09bd622bc723b55881dc541cd50747cbd08831c2a82d620f6d76'
            '29bd7b19cebf31dddb0cb3fe9d938a367e99fa045ac523014fc45d4021577e53'
            '4183dc3b5c17a0cb5fb66ada179b9bd2b43e997d3a9c854d19cf892ea6e524b9')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  sed -e "s|-Werror||g" -i CMakeLists.txt
  patch -p1 -i ${srcdir}/001-snappy-optional.patch
  patch -p1 -i ${srcdir}/leveldb-unbundle-gtest-benchmark.patch
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  [[ -d "${srcdir}"/build-${MSYSTEM}-static ]] && rm -rf "${srcdir}"/build-${MSYSTEM}-static
  mkdir -p "${srcdir}"/build-${MSYSTEM}-static && cd "${srcdir}"/build-${MSYSTEM}-static

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${extra_config[@]} \
    -DLEVELDB_USE_SNAPPY=OFF \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake --build .

  [[ -d "${srcdir}"/build-${MSYSTEM}-shared ]] && rm -rf "${srcdir}"/build-${MSYSTEM}-shared
  mkdir -p "${srcdir}"/build-${MSYSTEM}-shared && cd "${srcdir}"/build-${MSYSTEM}-shared

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${extra_config[@]} \
    -DLEVELDB_USE_SNAPPY=OFF \
    -DBUILD_SHARED_LIBS=ON \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  ${MINGW_PREFIX}/bin/ctest . || warning "Tests failed"

  cd "${srcdir}/build-${MSYSTEM}-shared"
  ${MINGW_PREFIX}/bin/ctest . || warning "Tests failed"
}

package() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

  cd "${srcdir}/build-${MSYSTEM}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

  install -Dm644 ${srcdir}/${_realname}-${pkgver}/LICENSE ${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
